package com.leyou.user.service;

import com.leyou.common.utils.NumberUtils;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import com.leyou.user.utils.CodecUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    static final String KEY_PREFIX = "user:code:phone:";

    static final Logger logger = LoggerFactory.getLogger(UserService.class);

    public Boolean checkData(String data, Integer type) {
        User record = new User();
        switch (type) {
            case 1:
                record.setUsername(data);
                break;
            case 2:
                record.setPhone(data);
                break;
            default:
                return null;
        }
        return userMapper.selectCount(record) == 0;
    }

    public Boolean sendVerifyCode(String phone) {
        //生成验证码
        String code = NumberUtils.generateCode(6);

        //发送短信
        try {
            Map<String, String> msg = new HashMap<>();
            msg.put("phone", phone);
            msg.put("code", code);

            amqpTemplate.convertAndSend("ly.sms.exchange", "sms.verify.code", msg);
            //将code存入redis
            redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);
            return true;
        } catch (Exception e) {
            logger.error("发送短信失败。phome:{},code:{}", phone, code);
            return false;
        }
    }

    public Boolean register(User user, String code) {
        String key = KEY_PREFIX + user.getPhone();
        //从redis取出验证码
        String codeCache = redisTemplate.opsForValue().get(key);
        //检查验证码是否正确
        if (!code.equals(codeCache)) {
            //不正确,返回
            return false;
        }
        user.setId(null);
        user.setCreated(new Date());
        //生成盐
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);
        //对密码进行加密
        user.setPassword(CodecUtils.md5Hex(user.getPassword(), salt));
        //写入数据库
        boolean boo = userMapper.insertSelective(user) == 1;
        //如果注册成功,删除redis中的code
        if (boo) {
            try {
                redisTemplate.delete(key);
            } catch (Exception e) {
                logger.error("删除缓存验证码失败,code:{}", code, e);
            }
        }
        return boo;
    }

    public User queryUser(String username, String password) {
        //查询
        User record = new User();
        record.setUsername(username);
        User user = userMapper.selectOne(record);
        //检验用户名
        if (user == null) {
            return null;
        }
        //检验密码
        if (!user.getPassword().equals(CodecUtils.md5Hex(password, user.getSalt()))) {
            return null;
        }
        //用户名密码都是正确
        return user;
    }
}
